﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using NUnit.Framework;

namespace TaskFramework.Tests
{
    [TestFixture]
    public class BatchScopeFixture
    {
        readonly Queue<TaskEvent> _taskEventQueue = new Queue<TaskEvent>();
        readonly Queue<BatchEvent> _batchEventQueue = new Queue<BatchEvent>();

        private void onTaskEvent(TaskEvent info)
        {
            lock (_taskEventQueue)
            {
                _taskEventQueue.Enqueue(info);
            }
        }

        [TearDown]
        public void Reset()
        {
            lock (_taskEventQueue)
            {
                _taskEventQueue.Clear();
            }
        }

        [Test]
        public void should_wrap_up_multiple_tasks_into_a_single_scope()
        {
            ITaskPool taskPool = new TaskPool(4);
            taskPool.WriteDebugInfo = true;
            ITaskDispatcher dispatcher = new TaskDispatcher(taskPool);
            dispatcher.AddTaskFactory(new QuickTaskFactory());
            dispatcher.TaskEvent += onTaskEvent;
            dispatcher.WriteDebugInfo = true;

            Task task1 = new QuickTask(new QuickTaskRequest(2, RouteType.RouteSingleRequestAndDecrementRouteCount, 50, false));

            taskPool.QueueTask(task1, onTaskEvent);

            dispatcher.RouteRequest(new QuickTaskRequest());

            int batchId;
            using (BatchScope scope = dispatcher.CreateBatchScope(onBatchEvent))
            {
                batchId = scope.BatchId;

                dispatcher.RouteRequest(new QuickTaskRequest(5, RouteType.RouteRequestInBatchAndSetRouteCountToZero, 50, false)); // elapsed at new task dequeue time: 50ms (ish)
                dispatcher.RouteRequest(new QuickTaskRequest(3, RouteType.RouteSingleRequestAndDecrementRouteCount, 50, false)); //elapsed at final routed task completion: 250ms (ish)
            }

            Thread.Sleep(300);

            Assert.AreEqual(1, _batchEventQueue.Count);
        }

        private void onBatchEvent(BatchEvent e)
        {
            _batchEventQueue.Enqueue(e);
        }
    }

    public interface IBatchHandler
    {
        
    }

    public class BatchHandler : IBatchHandler
    {
        
    }

    
}
